package com.chuji.crmcj.act;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.chuji.crmcj.R;
import com.chuji.crmcj.adapter.TenureAdapter;
import com.chuji.crmcj.adapter.TenureMagAdapter;
import com.chuji.crmcj.bean.CarModelInfo;
import com.chuji.crmcj.bean.FullPayInfo;
import com.chuji.crmcj.bean.GoodMan;
import com.chuji.crmcj.bean.TeunMagInfo;
import com.chuji.crmcj.utils.ConstantValue;
import com.chuji.crmcj.utils.DrawableUtils;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.view.FlowLayout;
import com.chuji.crmcj.view.QuickIndexBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 保有客户
 * Created by w.pitt on 2016/1/15.
 */
public class TenureListAct extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private QuickIndexBar mIndexBar;
    private ListView mTenuLv;
    private ArrayList<GoodMan> mPersons = new ArrayList<GoodMan>();
    private TextView mTvIndex;
    private TenureMagAdapter tenureMagAdp;
    private FullPayInfo fullPayInfo;
    private View view_right;
    private RelativeLayout mRlTitile;
    private FlowLayout mFlCarModel;
    private int width = UIUtils.dip2px(7);
    private int height = UIUtils.dip2px(4);
    private List<String> mCarModels = new ArrayList<String>();
    private ScrollView mScrollView;
    private GoodMan goodMan;
    private PopupWindow popupWindow;
    private GradientDrawable createDrawable;
    private TextView textView;
    private String companyID;
    private List<CarModelInfo.ApiParamObjEntity> mCalModelInfo;
    private CarModelInfo carModelInfo;
    private String currCarModel;
    private TextView view;
    private int roleType;
    private String userID;
    private TeunMagInfo teunMagInfo;
    private TenureAdapter tenureSaleAda;
    private View view_left;
    private List<FullPayInfo.ApiParamObjEntity> mFullPaylist;

    @Override
    protected void initView() {
        setContentView(R.layout.act_tenure_list);
        mRlTitile = (RelativeLayout) findViewById(R.id.rl_title);
        view_right = findViewById(R.id.view_right);
        mTenuLv = (ListView) findViewById(R.id.lv);
        mIndexBar = (QuickIndexBar) findViewById(R.id.index_bar);
        mTvIndex = (TextView) findViewById(R.id.tv_index);
        view_left = findViewById(R.id.view_left);
    }

    @Override
    protected void initData() {
        userID = SPUtils.getString(UIUtils.getContext(), "UserID", "");
        mTvBarTitle.setText("保有客户");
        companyID = SPUtils.getString(UIUtils.getContext(), "CompanyID", "");
        roleType = SPUtils.getInt(UIUtils.getContext(), "RoleType", -1);

        // 动态设置 mTenuLv 的 right 的距离 。放置重叠
        mTenuLv.setPadding(0, 0, UIUtils.dip2px(10), 0);

        reqNetData();
//      mTenuLv.setAdapter(new NameAdapter(getApplicationContext(), mPersons));
    }

    private void reqNetData() {
        //获取全部车型
        reqCarModel();
        if (roleType == 1) {
            //获取 保有客户
            reqTenCliList("");
        } else {
            reqMagCliList("");
        }
    }

    private void reqTenCliList(String carModel) {
        String strURL = String.format(UrlUtils.GETRETAINPASLIST + "&SalesID=%s&CarModel=%s&PageSize=10&PageIndex=%d", userID, carModel, 1);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                fullPayInfo = JSON.parseObject(s, FullPayInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (fullPayInfo.getApiParamObj().size() != 0) {
                            if (tenureSaleAda == null) {
                                mFullPaylist = fullPayInfo.getApiParamObj();
                                fillNameAndSort();
                                tenureSaleAda = new TenureAdapter(UIUtils.getContext(), mTenuLv, mFullPaylist, mPersons);
                                mTenuLv.setAdapter(tenureSaleAda);
                            } else {
                                mFullPaylist = tenureSaleAda.getList();
                                // 这个界面只有 重新加载
                                mFullPaylist.clear();
                                mFullPaylist.addAll(fullPayInfo.getApiParamObj());
                                fillNameAndSort();
                                tenureSaleAda.notifyDataSetChanged();
                            }
                        } else {
                            UIUtils.showToastSafe("无数据显示");
                        }
                    }
                });
            }
        });
    }

    private void reqMagCliList(String carModel) {
        String strURL = String.format(UrlUtils.HasCustomerPeter + "&UserID=%s&CarModel=%s", userID, carModel);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                teunMagInfo = JSON.parseObject(s, TeunMagInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (teunMagInfo.getApiParamObj().size() != 0) {
                            fillNameAndSort();
                            tenureMagAdp = new TenureMagAdapter(UIUtils.getContext(), mTenuLv, teunMagInfo, mPersons);
                            mTenuLv.setAdapter(tenureMagAdp);
                        } else {
                            UIUtils.showToastSafe("无数据显示");
                        }
                    }
                });
            }
        });
    }

    private void reqCarModel() {
        String strURL = String.format(UrlUtils.GetCarModelByCompanyID + "&CompanyID=%s", companyID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                carModelInfo = JSON.parseObject(s, CarModelInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        mCalModelInfo = new ArrayList<CarModelInfo.ApiParamObjEntity>();
                        if (carModelInfo.getApiParamObj().size() != 0) {
                            for (int i = 0; i < carModelInfo.getApiParamObj().size(); i++) {
                                mCalModelInfo.add(carModelInfo.getApiParamObj().get(i));
                                mCarModels.add(carModelInfo.getApiParamObj().get(i).getCarModel());
                            }
                        }
                    }
                });
            }
        });
    }

    private int mVerticalSpacing = UIUtils.dip2px(10);

    private void initCarModel() {
        /**
         * 设置搜索历史标签 流式布局
         */
        mFlCarModel.setPadding(mVerticalSpacing, mVerticalSpacing, mVerticalSpacing, mVerticalSpacing);
        // 设置纵轴间距
        mFlCarModel.setVerticalSpacing(mVerticalSpacing);
        mFlCarModel.setHorizontalSpacing(mVerticalSpacing);
    }

    private String carModel = "";


    @Override
    protected void initListener() {
        mIndexBar.setOnLetterChangeListener(new QuickIndexBar.OnLetterChangeListener() {
            @Override
            public void onLetterChange(String letter) {
                showText(letter);
                for (int i = 0; i < mPersons.size(); i++) {
                    goodMan = mPersons.get(i);
                    String firstPinyin = String.valueOf(goodMan.mPinyin.charAt(0));
                    if (TextUtils.equals(firstPinyin, letter)) {
                        mTenuLv.setSelection(i);
                        break;
                    }
                }
            }
        });
        view_right.setOnClickListener(this);
        mTenuLv.setOnItemClickListener(this);
        view_left.setOnClickListener(this);
    }

    private Handler mHandler = new Handler();

    protected void showText(String letter) {
        mIndexBar.setBackgroundColor(UIUtils.getColor(R.color.gray));
        mTvIndex.setVisibility(View.VISIBLE);
        mTvIndex.setText(letter);
        mHandler.removeCallbacksAndMessages(null);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mIndexBar.setBackgroundColor(UIUtils.getColor(R.drawable.transparent));
                mTvIndex.setVisibility(View.GONE);
            }
        }, 800);
    }

    private void fillNameAndSort() {
        if (roleType == 1) {
            for (int i = 0; i < fullPayInfo.getApiParamObj().size(); i++) {
                goodMan = new GoodMan(mFullPaylist.get(i).getName());
//            goodMan = new GoodMan(new Cheeses().NAMES[i]);
                mPersons.add(goodMan);
            }
        } else {
            for (int i = 0; i < teunMagInfo.getApiParamObj().size(); i++) {
                goodMan = new GoodMan(teunMagInfo.getApiParamObj().get(i).getName());
//            goodMan = new GoodMan(new Cheeses().NAMES[i]);
                mPersons.add(goodMan);
            }
        }
        Collections.sort(mPersons);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_left:
                finish();
                break;
            case R.id.view_right:
                CarModelPop();
                break;
            case R.id.tv_all_carmodel:
                reqTenCliList("");
                popupWindow.dismiss();
                break;
        }
    }

    private void CarModelPop() {
        // TextView contentView = new TextView(this);
        // contentView.setBackgroundColor(Color.RED);
        View contentView = View.inflate(this, R.layout.popu_car_model, null);
//        mFlCarModel = (FlowLayout) contentView.findViewById(R.id.fl_car_model);
        mFlCarModel = new FlowLayout(UIUtils.getContext());
        TextView mAllCarModel = (TextView) contentView.findViewById(R.id.tv_all_carmodel);
        mScrollView = (ScrollView) contentView.findViewById(R.id.sv_flow);
        mAllCarModel.setOnClickListener(this);

        /*初始化流式布局*/
        initCarModel();
        // 初始化气泡控件
        // 第一个参数:需要展示的view

        /**
         * 设置数据
         */
        setFlowData();
        popupWindow = new PopupWindow(contentView, RadioGroup.LayoutParams.MATCH_PARENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        // side旁边 点击旁边让小气泡消失
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        // //设置小气泡的背景。是一个透明色
        popupWindow.setBackgroundDrawable(UIUtils.getDrawable(R.drawable.listview_background));
        popupWindow.showAsDropDown(mRlTitile, 0, 0);
        /**
         * 搜索历史 点击监听
         */
        for (int i = 0; i < mCarModels.size(); i++) {
            final TextView view = (TextView) mFlCarModel.getChildAt(i);
            if (view != null) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String text = (String) view.getText();
                        if (roleType == 1) {
                            //获取 保有客户
                            reqTenCliList(text);
                        } else {
                            reqMagCliList(text);
                        }
                        popupWindow.dismiss();
                    }
                });
            }
        }
    }

    private String salerName = "";

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(this, ClientDetailAct.class);
        intent.putExtra("SOURCE", ConstantValue.TenureListAct);
        if (roleType == 1) {
            intent.putExtra("CustomerID", fullPayInfo.getApiParamObj().get(i).getCustomerID());
            intent.putExtra("CarModel", fullPayInfo.getApiParamObj().get(i).getCarModel());
            intent.putExtra("CreateTime", fullPayInfo.getApiParamObj().get(i).getCreateTime());
        } else {
            intent.putExtra("CustomerID", teunMagInfo.getApiParamObj().get(i).getCustomerID());
            intent.putExtra("CarModel", teunMagInfo.getApiParamObj().get(i).getCarModel());
            intent.putExtra("CreateTime", teunMagInfo.getApiParamObj().get(i).getLastTime());
            intent.putExtra("SalerName", teunMagInfo.getApiParamObj().get(i).getRealName());
        }
        startActivity(intent);
    }

    private void setFlowData() {
        Random mRandom = new Random();
        for (int i = 0; i < mCarModels.size(); i++) {
            currCarModel = mCarModels.get(i);
            if (currCarModel == null || currCarModel == "") {
                continue;
            }
            textView = new TextView(UIUtils.getContext());
            int red = 196;
            int green = 196;
            int blue = 196;

            int color = Color.rgb(red, green, blue);
            createDrawable = DrawableUtils.createDrawable(color, color, 10);
//            textView.setBackground(createDrawable);
            textView.setBackgroundDrawable(createDrawable);
            textView.setTextColor(UIUtils.getColor(R.color.white));
            String text = mCarModels.get(i);
            // 设置四周的距离
            textView.setPadding(width, height, width, height);
            // 设置文本控件居中
            textView.setGravity(Gravity.CENTER);
            // 设置字体颜色
//            textView.setTextColor(Color.rgb(0, 0, 0));
            // 设置值
            textView.setText(text);
            mFlCarModel.addView(textView);
        }
        mScrollView.addView(mFlCarModel);
    }
}
